import { useQuery } from "@tanstack/react-query";
import request from "../../utils/request";
import { filter, get, map, set } from "lodash";
import { useRef, useState } from "react";
import { Button, Col, Form, Input, message, Modal, Radio, Row, Space } from "antd";
import { FormInstance } from "antd/es/form/hooks/useForm";
import Upload from "../upload";
import CheckBoxGroup from "../CheckBoxGroup";
import { UploadOutlined } from "@ant-design/icons";
import newTask from "./index";

const getPatternList = async () => {
  const data = await request("/task/getPatternList");
  return map(data, (item) => ({
    key: item.id,
    label: item.title,
  }));
};
const getFileTypeList = async () => {
  const data = await request("/task/getFileTypeList");
  return map(data, (item) => ({
    key: item.id,
    label: item.title,
  }));
};

let callback;
export const registerCallback = (c: any) => {
  callback = c;
}

let addTask;
export const addTaskToNewTaskComp = () => {
  addTask?.();
}

const NewTask = () => {
  const formsRef = useRef<FormInstance[]>([])
  const [newTasks, setNewTasks] = useState<{
    id: number,
    visible: true,
    loading: false
  }[]>([])


  const { data: taskOptions = [] } = useQuery({
    queryFn: getPatternList,
  });

  const { data: patternList = [] } = useQuery({
    queryKey: ["patternList"],
    queryFn: getPatternList,
  });

  const { data: fileList = [] } = useQuery({
    queryKey: ["fileList"],
    queryFn: getFileTypeList,
  });

  addTask = () => {
    setNewTasks([...newTasks, {
      id: Date.now(),
      visible: true,
      loading: false,
    }])
  }

  const onCancel = (id: number) => {
    const idx = newTasks.findIndex(item => item.id === id);
    setNewTasks(filter(newTasks, (tar) => tar.id !== id))
    if (formsRef.current[idx])
      { // @ts-ignore
        formsRef.current[idx] = null;
      }
  }
  const onAddTask = async (idx: number, id: number) => {
    const form = formsRef.current[idx]
    if (!form) return;
    const values = await form.getFieldsValue();
    await request.post("/task", values);
    onCancel(id)
    message.success("新增成功");
    callback?.();
  };

  const onHide = (idx: number) => {
    const formInstance = formsRef.current[idx];
    const itemNewTask = newTasks[idx];
    const hasUploadFile = get(itemNewTask, 'loading', false) || formInstance.getFieldValue('url');
    console.log(get(itemNewTask, 'loading', false), 'loading')
    if (hasUploadFile) {
      set(newTasks, `[${idx}].visible`, false)
      setNewTasks([...newTasks])
    } else {
      onCancel(itemNewTask.id)
    }
  }

  return <>
    <div className="fixed bottom-[15px] right-[20px]">
      <Space>
        {newTasks.map((task, idx) => (
          <Button key={task.id} className="border backdrop-blur-2xl cursor-pointer" onClick={() => {
            task.visible = true;
            setNewTasks([...newTasks])
          }}>{`新增任务·${formsRef.current[idx]?.getFieldValue('task_name') || idx + 1}`}</Button>
        ))}
      </Space>
    </div>
    {newTasks.map((item, idx) => (
      <Modal
        key={item.id}
        open={item.visible}
        onCancel={() => onHide(idx)}
        footer={[<Button onClick={() => onHide(idx)}>收起</Button>, <Button type="primary" onClick={() => onAddTask(idx, item.id)}>提交</Button>]}
        width={800}
        okButtonProps={{
          loading: item.loading,
        }}
        title="新建任务"
        onOk={() => onAddTask(idx)}
      >
        <Form ref={form => {
          formsRef.current[idx] = form;
        }} name="control-hooks">
          <Form.Item name="task_name" label="任务名称">
            <Input placeholder="请输入任务名称" />
          </Form.Item>
          <Form.Item name="url" label="上传文件">
            <Upload
              maxCount={1}
              accept=".zip, .tar, .rar, .gz, .xz"
              listType="text"
              onLoading={(loading) => {
                item.loading = loading
                setNewTasks([...newTasks])
              }}
              onRemove={() => {
                item.loading = false;
                setNewTasks([...newTasks])
              }}
            >
              <Button icon={<UploadOutlined />}>
                上传压缩包(支持zip/tar/rar 格式)
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item name="media_type_list" label="文件类型">
            <CheckBoxGroup
              items={fileList}
              groupWrap={(v) => <Row>{v}</Row>}
              itemWrap={(v) => <Col span={24}>{v}</Col>}
            ></CheckBoxGroup>
          </Form.Item>
          <Form.Item name="pattern_info" label="业务模型">
            <CheckBoxGroup
              items={patternList}
              groupWrap={(v) => <Row gutter={6}>{v}</Row>}
              itemWrap={(v) => <Col>{v}</Col>}
            />
          </Form.Item>
          <Form.Item name="is_global_mode" label="全局模型">
            <Radio.Group>
              <Radio value="0">否</Radio>
              <Radio value="1">是</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    ))}
  </>
}

export default NewTask